import os
import time
import pandas as pd

os.chdir(os.path.dirname(__file__))
os.makedirs('log/', exist_ok=True)


def get_outdated_packages():
    # 获取需要更新的第三方库名
    os.system('pip list --outdate > outdated_packages.txt')
    print("完成提取所需更新第三方库名.")
    pf = pd.read_csv('outdated_packages.txt', skiprows=2, header=None, sep='\\s+')
    pf.columns = ['name', 'old', 'new', '_type']
    names = pf['name'].values
    return names


def batch_update():
    # 获取需要更新的第三方库名
    names = get_outdated_packages()
    n = len(names)
    cmd = 'python3 -m pip install --upgrade {package_name}'
    for i, name in enumerate(names):
        print("\n共%d个, 正在更新第%d个: %s." % (n, i+1, name))
        os.system(cmd.format(package_name=name))


def del_file():
    os.remove('outdated_packages.txt')


def main(delete=False):
    batch_update()
    if delete:
        del_file()


if __name__ == "__main__":
    start = time.time()
    print("开始更新......")
    main(delete=False)
    end = time.time()
    print("更新所有库耗时: %.5f seconds" % (end-start))
